package cn.lyh.FoodSystem.Controller;


import cn.lyh.FoodSystem.Dto.PageInfo;
import cn.lyh.FoodSystem.Dto.Result;
import cn.lyh.FoodSystem.Entity.Entry;
import cn.lyh.FoodSystem.Service.EntryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

import java.util.Objects;

import static cn.lyh.utils.HutoolJWTUtil.parseToken;

@RestController
@RequestMapping("/entry")
public class EntryController {


    @Autowired
    private  EntryService entryService;

    /**
   * 提交报名
   */
    @PostMapping("/addEntry")
    public Result addVideo(@Valid @RequestBody Entry entry, BindingResult bindingResult, @RequestHeader("token") String token){
        Result result = new Result();
        try {
            if (bindingResult.hasErrors()) {
                result.setCode(400);
                result.setMsg(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
                return result;
            }
            entry.setUserId(String.valueOf(parseToken(token)));
            return entryService.addEntry(entry);
        }catch (Exception e){
            result.setMsg("程序错误！");
            result.setCode(500);
            return result;
        }


    }

    /**
     * 查询报名用户信息(后台)
     */
    @PostMapping("/queryEntryAll")
    public Result queryEntryAll(@RequestBody PageInfo pageInfo){
        return entryService.queryEntryAll(pageInfo);
    }

    /**
     * 更新数据
     */
    @PostMapping("/updateEntry")
    public Result updateEntry(@RequestBody Entry entry){
        return entryService.updateEntry(entry);
    }

    /**
     * 删除数据
     */
    @PostMapping("/deleteEntry")
    public Result deleteEntry(@RequestBody Entry entry){
        return entryService.deleteEntry(entry);
    }

    /**
     * 用户查询自己的报名信息
     */
    @PostMapping("/queryEntry")
    public Result queryEntry(@RequestBody Entry entry,@RequestHeader("token") String token){
        Result result = new Result();
        try {
            entry.setUserId(String.valueOf(parseToken(token)));
           result = entryService.queryEntry(entry);
        }catch (Exception e){
            result.setMsg("程序错误！");
            result.setCode(500);
            return result;
        }
        return  result;
    }

}
